package com.yue.mytomcat.ex01.webcontainer;

import java.io.*;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/8/2<br/>
 *
 * @author QiuYang
 */
public class Response {
    private static final int BUFFER_SIZE = 1024;
    private Request request;
    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fileInputStream = null;

        try {
            File file = new File(HttpServer.WEB_ROOT, request.getUri());    // 更具请求的资源创建file 对象
            if (file.exists()) {
                fileInputStream = new FileInputStream(file);
                int c = fileInputStream.read(bytes, 0, BUFFER_SIZE);
                while(c != -1){
                    outputStream.write(bytes, 0, c);
                    c = fileInputStream.read(bytes, 0, BUFFER_SIZE);
                }
            }else {
                String errorMessage = "HTTP/1.1 404 File Not Found\r\nContent-Type:"+
                        "text/html\r\nContent-Length:23\r\n\r\n<h1>File Not Found</h1>";
                outputStream.write(errorMessage.getBytes());
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
